package com.lejin;



import com.lejin.usercenter.entity.SysUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.*;

/**
 * 生成token以及校验token相关方法
 */
public class JwtUtils {

    private static final String JWT_PAYLOAD_USER_KEY = "user";

    /**
     * 私钥加密token
     * @param userInfo   载荷中的数据
     * @param privateKey 私钥
     * @param expire     过期时间，单位分钟
     * @return JWT
     */
    public static String generateTokenExpireInMinutes(Object userInfo, PrivateKey privateKey, int expire) {
        //计算过期时间
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE,expire);

        return Jwts.builder()
                .claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))//将用户信息放入payload
                .setId(new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes())))
                .setExpiration(c.getTime())
                .signWith(privateKey, SignatureAlgorithm.RS256)
                .compact();
    }

    /**
     * 私钥加密token
     * @param userInfo   载荷中的数据
     * @param privateKey 私钥
     * @param expire     过期时间，单位秒
     * @return JWT
     */
    public static String generateTokenExpireInSeconds(Object userInfo, PrivateKey privateKey, int expire) {
        //计算过期时间
        Calendar c = Calendar.getInstance();
        c.add(Calendar.SECOND,expire);

        return Jwts.builder()
                .claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
                .setId(new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes())))
                .setExpiration(c.getTime())
                .signWith(privateKey, SignatureAlgorithm.RS256)
                .compact();
    }






    /**
     * 获取token中的用户信息
     * 解析令牌的方法
     *
     * @param token     用户请求中的令牌
     * @param publicKey 公钥
     * @return 用户信息
     */
    public static  Object getInfoFromToken(String token, PublicKey publicKey, Class userType) {
        //解析token
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);

        Claims body = claimsJws.getBody();//获取payload
        String userInfoJson = body.get(JWT_PAYLOAD_USER_KEY).toString();
        return JsonUtils.toBean(userInfoJson, userType);

    }

    public static void main(String[] args) {


        String path1 = null;
        try {
            path1 = ResourceUtils.getFile("classpath:rsa_pub").getPath();
        } catch (FileNotFoundException e) {
            System.out.println("ResourceUtils 错误");
            e.printStackTrace();
        }
        try {
            PublicKey publicKey = RsaUtils.getPublicKey(path1);
            Object fromToken = JwtUtils.getInfoFromToken("eyJhbGciOiJSUzI1NiJ9.eyJ1c2VyIjoie1widXNlcklkXCI6XCIyXCIsXCJ1c2VyTmFtZVwiOlwiMzQ0NDQ1XCIsXCJhY2NvdW50XCI6XCIxMjIyXCIsXCJzZXhcIjoxLFwicmVhbE5hbWVcIjpudWxsLFwiaW1hZ2VzXCI6XCJodHRwOi8vcmFtcmFiNGg3LmhuLWJrdC5jbG91ZGRuLmNvbS9jMi5wbmdcIixcInBhc3N3b3JkXCI6XCJcIixcInVzZXJUeXBlXCI6XCI2XCIsXCJyZW1hcmtcIjpudWxsLFwibG9naW5UaW1lXCI6bnVsbCxcImVuYWJsZWRcIjpudWxsLFwicm9sZUlkXCI6XCIxXCIsXCJzZWxmXCI6bnVsbCxcInBob25lXCI6bnVsbCxcImNyZWF0ZVRpbWVcIjpudWxsLFwidXBkYXRlVGltZVwiOjE2NTA2MzAwMDAwMDB9IiwianRpIjoiTldGaU56ZzRZVFF0TlRRNFlpMDBNV1ZrTFdKbE9EVXRNRFUxWkdSbE16Wm1PVGxpIiwiZXhwIjoxNjUwODkyMjkyfQ.YP3IFlePlzmtHV-Snilq655TX_w0JgrpTKXoKTtv1hG-Ui5QwvzwnmGLFJI3JlXNPj6_rtZ1bsJKBNAQLp4_4dudwEKhCX_DCV9XlNQRBgpemeJx0XhNduqO2q8ipbLhZQLZcgSlmixYZz3EX2pfLssxFRu6iJC4KmLbIk3hRHvERuvZ1ggerif4JHWAKjIQMTZK5y9PjgGCQwCOaSBd6PuVjrN8Tx6DqT5Srqhr64-dTIfBWElY8g4Way536JyzAp94XVyxcBHD3leAEfo1JA4Y8SqS_I8r4pXRNSN9EQVmd_UiFEEdRoB2HPxPLGWZy_OPJDi_sFSA_iNuZwsF7g", publicKey, SysUser.class);

            System.out.println(fromToken);

        } catch (Exception e) {
            System.out.println("RsaUtils 错误");
            e.printStackTrace();
        }
    }



}